package com.bll.tsdoa.utils;

import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * 分布式雪花算法ID生成器
 * 结构：0 | 时间戳(41位) | 数据中心ID(5位) | 机器ID(5位) | 序列号(12位)
 *
 * @author bll
 */
@Component
public class DefaultIdentifierGenerator {
    // 起始时间戳（2024-01-01 00:00:00）
    private final static long START_TIMESTAMP = 1704038400000L;

    // 各部分的位数
    private final static long DATA_CENTER_ID_BITS = 5L;
    private final static long WORKER_ID_BITS = 5L;
    private final static long SEQUENCE_BITS = 12L;

    // 最大值
    private final static long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 左移位
    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private final static long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

    private final long dataCenterId;
    private final long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    /**
     * 自动获取数据中心ID和机器ID（基于MAC地址和进程ID）
     */
/*    public DefaultIdentifierGenerator() {
        this.dataCenterId = getDataCenterId();
        this.workerId = getWorkerId();
        validateIds();
    }*/
    public DefaultIdentifierGenerator() {
        this.dataCenterId = getDataCenterId();
        this.workerId = getWorkerId();

        // 添加调试信息
        System.out.println("Generated DataCenterID: " + this.dataCenterId);
        System.out.println("Generated WorkerID: " + this.workerId);

        validateIds();
    }


    /**
     * 手动指定数据中心ID和机器ID
     */
    public DefaultIdentifierGenerator(long dataCenterId, long workerId) {
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
        validateIds();
    }

    private void validateIds() {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("Data center ID 必须在 0-" + MAX_DATA_CENTER_ID);
        }
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID 必须在 0-" + MAX_WORKER_ID);
        }
    }

    /**
     * 生成下一个ID（线程安全）
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        // 处理时钟回拨
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨拒绝生成ID，回拨时间：" + (lastTimestamp - timestamp) + "ms");
        }

        // 同一毫秒内生成
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) { // 当前毫秒序列号用尽
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 自动获取数据中心ID（基于MAC地址）
     */
/*    private long getDataCenterId() {
        try {
            NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            byte[] mac = network.getHardwareAddress();
            return ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
        } catch (Exception e) {
            return 1L; // 失败时返回默认值
        }
    }*/
    private long getDataCenterId() {
        try {
            NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            byte[] mac = network.getHardwareAddress();

            // 更安全的计算方式：取后两个字节的异或值并与31取模
            long id = ((0xFF & (long) mac[mac.length - 2]) ^ (0xFF & (long) mac[mac.length - 1])) % (MAX_DATA_CENTER_ID + 1);
            return id < 0 ? -id : id; // 确保非负
        } catch (Exception e) {
            System.err.println("自动获取DataCenterId失败，将使用默认值1，建议手动配置");
            return 1L; // 失败时返回安全值
        }
    }


    /**
     * 自动获取机器ID（基于进程ID）
     */
    private long getWorkerId() {
        String processId = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        return Long.parseLong(processId) % (MAX_WORKER_ID + 1);
    }
}
